package com.foo.CR;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

/**
 * Created by IntelliJ IDEA.
 * User: Tejas
 * Date: 12/28/10
 * Time: 11:21 AM
 *
 * This is the brain of the application and another entry point into the application.
 * This is a manifest registered receiver, hence will start receiving WiFi events as soon as App is installed.
 * This will perform the logic to figure out for which WiFi what ringer to select.
 * It will change the ringer settings by looking up into MyWiFiMap as necessary.
 * The application need not be running for this to happen.
 */
public class WifiChangeReceiver extends BroadcastReceiver
{
    private static final String TAG  = "CR"; // For logging purpose

    private static String _currentWiFi = "";

    private Context _context = null;
    private AudioManager _aMgr = null;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        _context = context;

        _aMgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        Log.d(TAG, " ");
        Log.d(TAG, "========= in onReceive  =======");
        String action = intent.getAction();
        Log.d(TAG, " Action : " + action);

        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) // Wifi SSID changed, also gets called on ON / OFF
                                                                    //  Cannot detect OFF, since cannot get the WifiState

        {
            Log.d(TAG, " Network state changed ");
            WifiManager wMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wInfo = wMgr.getConnectionInfo();
            String wifiName = wInfo.getSSID();

            Log.d(TAG, "========= wifiName = "+ wifiName +" =======");

            if (wifiName == null)
            {
                onWiFiDisconnected();
            }
            else
            {
                onWiFiConnected(wifiName);
            }

        }
        else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) // Wifi ON/OFF indication, wifiname here is unreliable
                                                                       // wifiname is null when WifiEnabled ! :(
        {
            Log.d(TAG, " Wifi state changed ");
            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
            switch (wifiState)
            {
                case WifiManager.WIFI_STATE_ENABLED:
                    Log.d(TAG, "WiFi Enabled");
                    onWiFiTurnedON(null);
                    break;
                case WifiManager.WIFI_STATE_DISABLED:
                    Log.d(TAG, "WiFi Disabled");
                    onWiFiTurnedOFF();
                    break;
                case WifiManager.WIFI_STATE_ENABLING:
                    Log.d(TAG, "WiFi Enabling");
                    break;
                case WifiManager.WIFI_STATE_DISABLING:
                    Log.d(TAG, "WiFi Disabling");
                    break;
                case WifiManager.WIFI_STATE_UNKNOWN:
                    Log.d(TAG, "WiFi Unknown");
                    break;

            }

        }

        Log.d(TAG, " ");
    }

    /**
     * Later make these abstract
     */

    // Don't really need this function
    // We'll be getting the "Enabled" when we are once connected
    // If we are not connected - doesn't matter - no change !
    void onWiFiTurnedON(String currentSSID)
    {
        Log.i(TAG, "WiFi Turned ON");
    }

    void onWiFiTurnedOFF()
    {
        Log.i(TAG, "WiFi Turned OFF");
        Notifier.notify(_context, "WiFi is OFF", "CR can no longer handle Ringer");

        //TODO
        // Notify user -> Clicking it opens the Sound Settings Page
                         // Otherwise user can clear it
    }

    void onWiFiConnected(String newSSID)
    {
        Log.i(TAG, "WiFi Connected to [" + newSSID + "]");
        Log.i(TAG, "Old WiFi [" + _currentWiFi + "]");
        _currentWiFi = newSSID;

        // See if newSSID is in MyWiFiMap
        MyWiFiMap myWifiMap = MyWiFiMap.getMyWifiMap(_context);
        int ringerState = myWifiMap.getActionforSSID(newSSID);

        if (ringerState != Constants.RINGER_ACTION_NOT_FOUND)
        {

            Log.i(TAG, " ringerState = " + ringerState);
            //TODO
            // Remove Notifications
            switch (ringerState)
            {
                case Constants.RINGER_ACTION_SILENT:
                    Log.i(TAG, "Setting ringerState = SILENT");
                    if(_aMgr.getRingerMode() != AudioManager.RINGER_MODE_SILENT)
                    {
                        _aMgr.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                        Notifier.notify(_context, Constants.RingerNotificationTitle, Constants.RingerNotifTextSilent );
                    }
                    break;
                case Constants.RINGER_ACTION_NORMAL:
                    Log.i(TAG, "Setting ringerState = NORMAL");
                    if(_aMgr.getRingerMode() != AudioManager.RINGER_MODE_NORMAL)
                    {
                        _aMgr.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                        Notifier.notify(_context, Constants.RingerNotificationTitle, Constants.RingerNotifTextNormal );
                    }
                    break;
                case Constants.RINGER_ACTION_VIBRATE:
                    Log.i(TAG, "Setting ringerState = VIBRATE");
                    if(_aMgr.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE)
                    {
                        _aMgr.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                        Notifier.notify(_context, Constants.RingerNotificationTitle, Constants.RingerNotifTextVibrate );
                    }
                    break;
                case Constants.RINGER_ACTION_LOUD:
                    Log.i(TAG, "Setting ringerState = LOUD");
                    //if(_aMgr.getRingerMode() != AudioManager.RINGER_MODE_NORMAL)
                    //if(_aMgr.getStreamVolume(AudioManager.STREAM_RING) != _aMgr.getStreamMaxVolume(AudioManager.STREAM_RING))
                    {
                        _aMgr.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                        _aMgr.setStreamVolume(AudioManager.STREAM_RING, _aMgr.getStreamMaxVolume(AudioManager.STREAM_RING), 0);
                        Notifier.notify(_context, Constants.RingerNotificationTitle, Constants.RingerNotifTextLoud );
                    }
                    break;

            }
        }
        // If not, do nothing !
        else
        {
            Log.i(TAG, " No Ringer Config found for = " + newSSID);
        }
    }

    void onWiFiDisconnected()
    {
        Log.i(TAG, "WiFi Disconnected Old : [" + _currentWiFi + "]");
        _currentWiFi = "";
        // Do nothing
    }
}
